<?php

namespace app\achievement\controller;

use app\common\model\Engineers;
use app\common\model\MenuModel;
use app\common\model\OaAchievementWorkersModel;
use app\common\model\OaEngineersPerformanceModel;
use app\common\model\WorkOrderModel;
use app\common\model\CustomerModel;
use app\common\model\OaWorkersModel;
use app\common\model\FollowModel;
use app\common\model\Operation;
use app\common\model\Administrative;
use app\common\model\ChannelModel;
use app\common\model\ChannelPromotersModel;
use app\common\model\WithdrawModel;
use think\Db;

/**
 *    总后台首页  控制器
 * Class Index
 * @package app\achievement\controller
 */
class Index extends Base
{

    protected $customer_model;
    protected $work_order_model;
    protected $oa_workers_model;
    protected $follow_model;
    protected $oa_achievement_workers_model;
    protected $oa_engineers_performance_model;
    protected $engineers_model;
    protected $operation;
    protected $administrative;
    protected $channel_model;
    protected $channel_promoters_model;
    protected $withdraw_model;

    // 初始化构造方法，实例化模型
    public function __construct()
    {
        parent::__construct();
        $this->customer_model = new CustomerModel();  // 用户模型
        $this->work_order_model = new WorkOrderModel(); // 工单模型
        $this->oa_workers_model = new OaWorkersModel();
        $this->follow_model = new FollowModel();
        $this->oa_achievement_workers_model = new OaAchievementWorkersModel();  // 职工业绩表模型
        $this->oa_engineers_performance_model = new OaEngineersPerformanceModel();  // 工程人员业绩模型
        $this->engineers_model = new Engineers();  // 工程人员模型
        $this->operation = new Operation();  // 区域合伙人模型
        $this->administrative = new Administrative();  // 行政中心模型
        $this->channel_model = new ChannelModel();  // 渠道模型
        $this->channel_promoters_model = new ChannelPromotersModel();  // 渠道推广模型
        $this->withdraw_model = new WithdrawModel();  // 提现模型
    }

    public function index()
    {
        return $this->fetch('/index');
    }

    public function doindex()
    {
        // 获取今日时间戳
        $today_start = strtotime(date('Y-m-d 00:00:00'));
        $today_end = strtotime(date('Y-m-d H:i:s'));
        $between = ['between', [$today_start, $today_end]];

        // 今日结算金额---业务员、渠道商、推广、区域合伙人、合伙人————————————————————————
        $where['a.add_time'] = $between;
        $where['qualified'] = 1;
        $where['c.company_id'] = $this->company_id;
        $join = [
            ['oa_achievement o', 'o.achievement_id = a.achievement_id', 'LEFT'],
            ['contract c', 'c.contract_no = o.contract_number', 'LEFT'],
        ];
        $field = 'sum(a.money) money';
        $oa_today_money= $this->oa_achievement_workers_model->getOne($where, $field,$join)['money'] ?? 0;

        unset($where['a.add_time']);
        // 累计结算金额---业务员
        $oa_total_money= $this->oa_achievement_workers_model->getOne($where, $field,$join)['money'] ?? 0;

        unset($where);
        // 今日结算金额---工程人员——————————————————————————————————————
        $where['a.add_time'] = $between;
        $join = [
            ['engineers e', 'e.engineers_id = a.engineers_id', 'left'],  // 工程人员表---工程人员业绩表
            ['administrative_info ai', 'ai.a_id=e.administrative_id', 'left']
        ];
        $where['ai.company_id'] = $this->company_id;
        $en_today_money= $this->oa_engineers_performance_model->getOne($where, $field,$join)['money'] ?? 0;
        unset($where['a.add_time']);

        // 累计结算金额---工程人员
        $en_total_money= $this->oa_engineers_performance_model->getOne($where, $field,$join)['money'] ?? 0;

        //合计结算金额————————————————————————————
        $data['today_money']=$oa_today_money+$en_today_money;
        $data['total_money']=$oa_total_money+$en_total_money;
        unset($where);

        // 业务员今日提现——————————————————————————————
        $where['complete_time'] = $between;
        $where['cash_order_state'] = 2;
        $where['play_money_state'] = ['IN',[2,3]];
        $where['c.user_belong_to_company'] = $this->company_id;
        $where['a.role'] = 6;
        $field = 'sum(cash_order_money) money';
        $join = [
            ['oa_workers ow','ow.workers_id=a.uid','left'],
            ['customer c','c.user_id=ow.user_id','left'],
        ];
        //手续费
        //$oa_today_payment_fee = $this->withdraw_model->getOne($where, 'sum(a.payment_fee) today_payment_fee',$join)['today_payment_fee'] ?? 0;
        //今日提现打款
        $oa_today_cash_money= $this->withdraw_model->getOne($where, $field,$join)['money'] ?? 0;
        $oa_today_withdraw_money=formatMoneys($oa_today_cash_money,2);//今日总的提现金额=提现金额+手续费
        unset($where['complete_time']);
        //业务员累计提现
        //$oa_total_payment_fee= $this->withdraw_model->getOne($where, 'sum(a.payment_fee) total_payment_fee',$join)['total_payment_fee'] ?? 0;
        $oa_total_cash_money= $this->withdraw_model->getOne($where, $field,$join)['money'] ?? 0;
        $oa_total_withdraw_money=formatMoneys($oa_total_cash_money,2);

        //渠道商今日提现————————————————————————————
        $where['complete_time'] = $between;
        $where['a.role'] = 4;
        $join = [
            ['customer c','c.user_id=a.uid','left'],
        ];
         //手续费
        //$ch_today_payment_fee = $this->withdraw_model->getOne($where, 'sum(a.payment_fee) today_payment_fee',$join)['today_payment_fee'] ?? 0;
        //今日提现打款
        $ch_today_cash_money= $this->withdraw_model->getOne($where, $field,$join)['money'] ?? 0;
        $ch_today_withdraw_money=formatMoneys($ch_today_cash_money,2);//今日总的提现金额=提现金额+手续费

        unset($where['complete_time']);
        //渠道累计提现
        //$ch_total_payment_fee= $this->withdraw_model->getOne($where, 'sum(a.payment_fee) total_payment_fee',$join)['total_payment_fee'] ?? 0;
        $ch_total_cash_money = $this->withdraw_model->getOne($where, $field,$join)['money'] ?? 0;
        $ch_total_withdraw_money=formatMoneys($ch_total_cash_money,2);
        unset($where);

        //工程人员今日提现————————————————————————————————————————————————————
        $where['complete_time'] = $between;
        $where['cash_order_state'] = 2;
        $where['play_money_state'] = ['IN',[2,3]];
        $where['m.company_id'] = $this->company_id;
        $where['a.role'] = 5;
        $join = [
            ['engineers e','e.engineers_id=a.uid','left'],
            ['administrative_info m','m.a_id=e.administrative_id','left'],
        ];
        //手续费
        //$en_today_payment_fee = $this->withdraw_model->getOne($where, 'sum(a.payment_fee) today_payment_fee',$join)['today_payment_fee'] ?? 0;
        //今日提现打款
        $en_today_cash_money= $this->withdraw_model->getOne($where, $field,$join)['money'] ?? 0;
        $en_today_withdraw_money=formatMoneys($en_today_cash_money,2);//今日总的提现金额=提现金额+手续费
        unset($where['complete_time']);
        //工程人员累计提现
        //$en_total_payment_fee= $this->withdraw_model->getOne($where, 'sum(a.payment_fee) total_payment_fee',$join)['total_payment_fee'] ?? 0;
        $en_total_cash_money = $this->withdraw_model->getOne($where, $field,$join)['money'] ?? 0;
        $en_total_withdraw_money=formatMoneys($en_total_cash_money,2);
        unset($where);

        //区域合伙人、城市合伙人今日提现————————————————————————————————————
        $wheres['complete_time'] = $between;
        $wheres['cash_order_state'] = 2;
        $wheres['play_money_state'] = ['IN',[2,3]];
        $wheres['role'] = ['IN',[1,2,3]];
        $field = 'cash_order_money,role,uid';
        $admin_today_list= $this->withdraw_model->getAll($wheres,$field,1,-1,'','uid,role');
        $today_money=0;
        if(!empty($admin_today_list)){
            foreach ($admin_today_list as $k=>$v){
                if($v['role']==2){//运营商
                    $operation=$this->operation->findOperation(['o_id'=>$v['uid'],'company_id'=>$this->company_id]);
                    if($v['uid']==$operation['o_id']){
                        $today_money+=$v['cash_order_money']??0;
                    }
                }else if($v['role']==3){//城市合伙人
                    $operation=$this->operation->findAdministrative(['a_id'=>$v['uid'],'company_id'=>$this->company_id]);
                    if($v['uid']==$operation['a_id']){
                        $today_money+=$v['cash_order_money']??0;
                    }

                }

            }
        }
        $admin_today_money=$today_money?formatMoneys($today_money,2):0;
        unset($wheres['complete_time']);
        //区域合伙人、城市合伙人累计提现——————————————————————————————————————————————
        $admin_total_list= $this->withdraw_model->getAll($wheres,$field,1,-1,'','uid,role');
        $total_money=0;
        if(!empty($admin_total_list)){
            foreach ($admin_total_list as $k=>$v){
                if($v['role']==2){//运营商
                    $operation=$this->operation->findOperation(['o_id'=>$v['uid'],'company_id'=>$this->company_id]);
                    if($v['uid']==$operation['o_id']){
                        $total_money+=$v['cash_order_money']??0;
                    }
                }else if($v['role']==3){//城市合伙人
                    $operation=$this->operation->findAdministrative(['a_id'=>$v['uid'],'company_id'=>$this->company_id]);
                    if($v['uid']==$operation['a_id']){
                        $total_money+=$v['cash_order_money']??0;
                    }

                }

            }
        }
        $admin_total_money=$total_money?formatMoneys($total_money,2):0;
        //累计提现————————————————————————————————
        $data['today_cash_money']=$oa_today_withdraw_money+$ch_today_withdraw_money+$en_today_withdraw_money+$admin_today_money;
        $data['total_cash_money']=$oa_total_withdraw_money+$ch_total_withdraw_money+$en_total_withdraw_money+$admin_total_money;

        /*****************************/
        /*//查询当前公司的所有区域合伙人和城市合伙人
        $o_id=[];
        $a_id=[];
        $operation=$this->operation->getAll(['company_id'=>$this->company_id],'o_id');
        foreach ($operation as $k=>$v){
            array_push($o_id,$v['o_id']);
        }
        $administrative=$this->administrative->getAll(['company_id'=>$this->company_id],'a_id');
        foreach ($administrative as $k=>$v){
            array_push($a_id,$v['a_id']);
        }*/
        /*************************/

        // 今日新增业务员————————————————————————————————————————————————
        $where['a.add_time'] = $between;
        $where['is_dealer'] = 1;
        $where['account_status'] = 1;
        $where['user_belong_to_company'] = $this->company_id;
        $data['today_add_workers'] = $this->customer_model->getCount($where);
        unset($where['a.add_time']);
        // 累计业务员数
        $data['total_workers'] = $this->customer_model->getCount($where);
        unset($where);

        // 今日新增工程人员——————————————————————————————————————————————————
        $where['reg_time'] = $between;
        $where['engineers_status'] = 2;
        $where['ai.company_id'] = $this->company_id;
        $join = [
            ['administrative_info ai', 'ai.a_id=e.administrative_id', 'left']
        ];
        $data['today_add_engineers'] = $this->engineers_model->getCount($where, $join);
        unset($where['reg_time']);
        // 累计工程人员数
        $data['total_engineers'] = $this->engineers_model->getCount($where,$join);
        unset($where);

        // 统计近7天走势图-----------------------------------------------------
        $seven = [];
        $data['seven'] = [];
        //近7天日期
        for ($i = 0; $i < 7; $i++) {
            $seven[$i]['start'] = date('Y-m-d 00:00:00', strtotime('+' . $i - 6 . ' days', time()));
            $seven[$i]['end'] = date('Y-m-d 23:59:59', strtotime('+' . $i - 6 . ' days', time()));
            $seven[$i]['time'] = date('m.d', strtotime('+' . $i - 6 . ' days', time()));
            array_push($data['seven'], date('m.d', strtotime('+' . $i - 6 . ' days', time())));
        }

        // 结算金额走势————————————————————————
        foreach ($seven as $k => $v) {
            // 近7天结算金额---业务员、渠道商、推广、区域合伙人、合伙人——————————————————————————————
            $where['a.add_time'] = ['between', [strtotime($v['start']), strtotime($v['end'])]];
            $where['qualified'] = 1;
            $where['c.company_id'] = $this->company_id;
            $field = 'sum(a.money) money';
            $join = [
                ['oa_achievement o', 'o.achievement_id = a.achievement_id', 'LEFT'],
                ['contract c', 'c.contract_no = o.contract_number', 'LEFT'],
            ];
            $data['seven_day_money'][$k] = $this->oa_achievement_workers_model->getOne($where, $field,$join)['money'] ?? 0;
            unset($where);
            // 近7天结算金额---工程人员——————————————————————————————————————————————
            $join = [
                ['engineers e', 'e.engineers_id = a.engineers_id', 'left'],  // 工程人员表---工程人员业绩表
                ['administrative_info ai', 'ai.a_id=e.administrative_id', 'left']
            ];
            $where['ai.company_id'] = $this->company_id;
            $where['a.add_time'] = ['between', [strtotime($v['start']), strtotime($v['end'])]];;
            $data['seven_day_money'][$k] += $this->oa_engineers_performance_model->getOne($where, $field,$join)['money'] ?? 0;
            unset($where);
        }


        // 提现打款走势————————————————————————————
        foreach ($seven as $k => $v) {
            $data['seven_day_cash_money'][$k]=0;
            // 近7天提现打款——业务员————————————————
            $where['complete_time'] = ['between', [strtotime($v['start']), strtotime($v['end'])]];
            $where['cash_order_state'] = 2;
            $where['play_money_state'] = ['IN',[2,3]];
            $where['user_belong_to_company'] = $this->company_id;
            $where['a.role'] = 6;
            $field = 'sum(cash_order_money) money';
            $join = [
                ['oa_workers ow','ow.workers_id=a.uid','left'],
                ['customer c','c.user_id=ow.user_id','left'],
            ];
            $workers_money = $this->withdraw_model->getOne($where, $field,$join)['money'] ?? 0;
            $data['seven_day_cash_money'][$k]+=formatMoneys($workers_money,2);

            // 近7天提现打款——渠道商、推广员————————————————
            $join = [
                ['customer c','c.user_id=a.uid','left'],
            ];
            $where['a.role'] = 4;
            $channel_money=$this->withdraw_model->getOne($where, $field,$join)['money'] ?? 0;
            $data['seven_day_cash_money'][$k]+=formatMoneys($channel_money,2);
            unset($where);

            // 近7天提现打款——工程人员————————————————
            $where['complete_time'] = ['between', [strtotime($v['start']), strtotime($v['end'])]];
            $where['cash_order_state'] = 2;
            $where['play_money_state'] = ['IN',[2,3]];
            $where['a.role'] = 5;
            $where['m.company_id'] = $this->company_id;
            $join = [
                ['engineers e','e.engineers_id=a.uid','left'],
                ['administrative_info m','m.a_id=e.administrative_id','left'],
            ];
            $engineers_money=$this->withdraw_model->getOne($where, $field,$join)['money'] ?? 0;
            $data['seven_day_cash_money'][$k]+=formatMoneys($engineers_money,2);
            unset($where);

            // 近7天提现打款——区域合伙人————————————————
            $where['complete_time'] = ['between', [strtotime($v['start']), strtotime($v['end'])]];
            $wheres['cash_order_state'] = 2;
            $wheres['play_money_state'] = ['IN',[2,3]];
            $where['a.role'] = 2;
            $where['o.company_id'] = $this->company_id;
            $join = [
                ['operation_info o','o.o_id=a.uid','left'],
            ];
            $operation_money=$this->withdraw_model->getOne($where, $field,$join)['money']??0;
            $data['seven_day_cash_money'][$k]+=formatMoneys($operation_money,2);
            unset($where);

            // 近7天提现打款——城市合伙人————————————————
            $where['complete_time'] = ['between', [strtotime($v['start']), strtotime($v['end'])]];
            $wheres['cash_order_state'] = 2;
            $wheres['play_money_state'] = ['IN',[2,3]];
            $where['a.role'] = 3;
            $where['o.company_id'] = $this->company_id;
            $join = [
                ['administrative_info o','o.a_id=a.uid','left'],
            ];
            $administrative_money=$this->withdraw_model->getOne($where, $field,$join)['money']??0;
            $data['seven_day_cash_money'][$k]+=formatMoneys($administrative_money,2);
            unset($where);

        }

        // 业绩排名业务员、区域合伙人、城市合伙人、渠道商、渠道推广员——————————————————————————————————————
        $join=[
            ['oa_achievement h', 'a.achievement_id = h.achievement_id', 'LEFT'],
            ['contract c', 'c.contract_no = h.contract_number', 'LEFT'],
        ];
        $where['c.company_id'] = $this->company_id;
        $achieve_list=$this->oa_achievement_workers_model->getJoinGroupAll($where,'sum(a.money) money,a.workers_id,a.role',$join,'a.workers_id,a.role',1,15,'money desc');
        if(!empty($achieve_list)){
            foreach ($achieve_list as $k=>$v){
                if($v['role']==1){
                    //业务员
                    $workers_rank=$this->oa_workers_model->getOne(['workers_id'=>$v['workers_id'],'workers_status'=>1],'workers_name');
                    $data['workers_rank'][$k]['workers_name']=$workers_rank['workers_name']??'';
                    $data['workers_rank'][$k]['money']=$v['money']??'';
                    ksort($data['workers_rank']);
                }else if($v['role']==2){
                    //区域合伙人
                    $operation=$this->operation->findOne(['o_id'=>$v['workers_id']],'company_name');
                    $data['operation_rank'][$k]['company_name']=$operation['company_name']??'';
                    $data['operation_rank'][$k]['money']=$v['money']??'';
                    ksort($data['operation_rank']);
                }else if($v['role']==3){
                    //城市合伙人
                    $administrative=$this->administrative->findOne(['a_id'=>$v['workers_id']],'company_name');
                    $data['administrative_rank'][$k]['company_name']=$administrative['company_name']??'';
                    $data['administrative_rank'][$k]['money']=$v['money']??'';
                    ksort($data['administrative_rank']);
                }else if($v['role']==4){
                    //渠道商
                    $channel_rank=$this->channel_model->getOne(['id'=>$v['workers_id']],'name');
                    $data['channel_rank'][$k]['name']=$channel_rank['name']??'';
                    $data['channel_rank'][$k]['money']=$v['money']??'';
                    ksort($data['channel_rank']);
                }else{
                    //渠道推广
                    $channel_promoters_rank=$this->channel_promoters_model->getOne(['channel_promoter_id'=>$v['workers_id']],'name');
                    $data['channel_promoters_rank'][$k]['name']=$channel_promoters_rank['name']??'';
                    $data['channel_promoters_rank'][$k]['money']=$v['money']??'';
                    ksort($data['channel_promoters_rank']);
                }
            }
        }
        unset($where);
        // 工程业绩排名
        $join = [
            ['engineers e', 'e.engineers_id = a.engineers_id', 'left'],  // 工程人员表---工程人员业绩表
            ['administrative_info ai', 'ai.a_id=e.administrative_id', 'left']
        ];
        $where['ai.company_id'] = $this->company_id;
        $where['engineers_status'] = 2;
        $field = 'sum(a.money) money,a.engineers_id,e.engineers_name';
        $group = 'a.engineers_id';
        $order = 'money DESC';
        $data['engineers_rank'] = $this->oa_engineers_performance_model->getJoinGroupAll($where, $field, $join, $group, 1, 15, $order);
        unset($where);


        // 模板赋值
        $this->assign('data', $data);
        // 调用视图
        return $this->fetch('index');
    }

    /**
     * 查询子菜单栏
     */
    public function MenuList()
    {
        if (request()->isPost()) {
            $meun = new MenuModel();
            $id = input("param.id");
            $data = $meun->getSubmenu($id, $this->set['auth_rule'], session($this->set['db_name'] . 'rule'));
            return json(['code' => 1, 'msg' => '', 'data' => $data]);
        }
    }

}
